/*
* 枷锁
* */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

#define MAXSIZE 8192

int main(int argc, char * argv[]) {
	int handle[2];
	char buf[MAXSIZE];
	pid_t pid1, pid2;

	while(pipe(handle) == -1) {
		perror("pipe");
		// exit(EXIT_FAILURE);
	}

	while((pid1 = fork()) == -1) {
		perror("fork pid1");
		// exit(EXIT_FAILURE);
	}

	if(pid1 == 0) {
		lockf(handle[1], F_LOCK, 0);
		strcpy(buf,"Child process 1 is sending a message!\n");
		write(handle[1], buf, strlen(buf));
		sleep(2);
		lockf(handle[1], F_ULOCK, 0);
		exit(EXIT_SUCCESS);
	} else {
		while((pid2 = fork()) == -1) {
			perror("fork pid2");
		}
		if(pid2 == 0) {
			lockf(handle[1], F_LOCK, 0);
			strcpy(buf, "Child process 2 is sending a message!\n");
			write(handle[1], buf, strlen(buf));
			sleep(2);
			lockf(handle[1], F_ULOCK, 0);
			exit(EXIT_SUCCESS);
		} else {
			waitpid(pid1, 0, 0);
			while((read(handle[0], buf, MAXSIZE)) > 0)
				write(STDOUT_FILENO, buf, strlen(buf));
			// sleep(5);
			waitpid(pid2, 0, 0);
			while((read(handle[0], buf, MAXSIZE)) > 0)
				write(STDOUT_FILENO, buf, strlen(buf));
			close(handle[0]);
			close(handle[1]);
			exit(EXIT_SUCCESS);
		}
	}

	return 0;
}
